package org.simin.smim.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.simin.smim.model.Message;

public class Pipe {
	public static final int PORT = 1219;
	private static Socket socket;

	private Socket getSocket() throws IOException {
		if (socket == null) {
			ServerSocket ss = new ServerSocket(PORT);
			socket = ss.accept();
		}
		return socket;
	}

	public void send(Message message) throws IOException,
			ClassNotFoundException {
		Socket s = new Socket(message.getReceiver(), PORT);
		ObjectOutputStream oos = new ObjectOutputStream(
				new BufferedOutputStream(s.getOutputStream()));
		oos.writeObject(message);
		oos.flush();
		oos.close();
		s.close();
	}

	public Message receive() throws IOException, Exception {
		socket = getSocket();
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
				socket.getInputStream()));
		Message message = null;
		message = (Message) ois.readObject();
		ois.close();
		return message;
	}

	public String getLocal() throws UnknownHostException {
		String localhost = new String();
		localhost = InetAddress.getLocalHost().getHostAddress();
		return localhost;
	}
}